package AssetBasicInfo

import (
	safesql "ToolLibray/Sql"
	"ToolLibray/jwtx"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"property_api/internal/svc"
	"property_api/internal/types"
	"property_api/utils/result"
	"property_api/utils/xform"
	"property_service/property_service"
)

type AddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Add 添加资产信息的逻辑
func (l *AddLogic) Add(req *types.AssetBasicInfo) (resp *types.Response, err error) {
	// 设置租户ID，从上下文中获取
	tenantID := jwtx.GetUserTenantId64(l.ctx)
	// 设置创建用户和更新用户，从上下文中获取
	userIdStr := xform.Int64ToString(jwtx.GetUserId(l.ctx))

	// 调用服务层方法，添加资产信息记录
	//	查询指定数据，赋值
	// 查询产地表
	if req.CountryOfOriginID != 0 {
		//查询产地表
		sql, err := safesql.Replace("select origin_name from origin_addition where id = ?", req.CountryOfOriginID)
		if err != nil {
			return result.Err(err).End()
		}
		CountryOfOrigin, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})

		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if CountryOfOrigin == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的产地信息", req.CountryOfOriginID)).End()
		}

		req.CountryOfOrigin = CountryOfOrigin.Str
	}

	//查询使用科室
	if req.UsageRoomID != 0 {
		//查询使用科室
		sql, err := safesql.Replace("select name from hospital_department where id = ?", req.UsageRoomID)
		if err != nil {
			return result.Err(err).End()
		}
		UsageRoom, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})
		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if UsageRoom == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的使用科室信息", req.UsageRoomID)).End()
		}

		req.UsageRoom = UsageRoom.Str
	}

	// 查询品牌
	if req.BrandID != 0 {
		//查询使用科室
		sql, err := safesql.Replace("select brand_name from brand_addition where id = ?", req.BrandID)
		if err != nil {
			return result.Err(err).End()
		}
		Brand, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})
		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if Brand == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的品牌信息", req.BrandID)).End()
		}

		req.Brand = Brand.Str
	}

	// 查询供应商
	if req.SupplierID != 0 {
		//查询使用科室
		sql, err := safesql.Replace("select supplier_level_name from supplier_level_addition where id = ?", req.SupplierID)
		if err != nil {
			return result.Err(err).End()
		}
		Supplier, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})
		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if Supplier == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的供应商信息", req.SupplierID)).End()
		}

		req.SupplierName = Supplier.Str
	}

	//管理科室
	if req.ManageRoomID != 0 {
		//查询使用科室
		sql, err := safesql.Replace("select name from hospital_department where id = ?", req.ManageRoomID)
		if err != nil {
			return result.Err(err).End()
		}
		ManageRoom, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})
		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if ManageRoom == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的管理科室信息", req.ManageRoomID)).End()
		}

		req.ManageRoom = ManageRoom.Str
	}

	//生产厂商
	if req.ManufacturersID != 0 {
		//查询使用科室
		sql, err := safesql.Replace("select name from vendor_info where id = ?", req.ManufacturersID)
		if err != nil {
			return result.Err(err).End()
		}
		ManufacturersID, err := l.svcCtx.CustomizeService.SelectBySql(l.ctx, &property_service.Sql{
			Sql: sql,
		})
		if err != nil {
			return result.Err(err).End()
		}
		// 检查查询结果是否存在
		if ManufacturersID == nil {
			return result.Err(fmt.Errorf("未找到ID为%d的生产厂商信息", req.ManufacturersID)).End()
		}

		req.ManufacturersName = ManufacturersID.Str
	}
	// 服务层方法 AssetBasicInfoAdd 会处理实际的数据库插入操作
	res, err := l.svcCtx.AssetService.AssetBasicInfoAdd(l.ctx, &property_service.AssetBasicInfo{
		AssetCode:             req.AssetCode,             // 资产编码
		AssetName:             req.AssetName,             // 资产名称
		AssetStatus:           req.AssetStatus,           // 资产状态
		SlMj:                  req.SlMj,                  //数量面积
		StatusID:              req.StatusID,              // 状态ID(关联状态表)
		AssetCategory:         req.AssetCategory,         // 资产分类
		AssetCategoryID:       req.AssetCategoryID,       // 资产分类ID
		AssetValue:            req.AssetValue,            // 资产原值
		AssetSerialNo:         req.AssetSerialNo,         // 资产序列号
		CountryOfOrigin:       req.CountryOfOrigin,       // 产地
		CountryOfOriginID:     req.CountryOfOriginID,     // 产地ID
		StorageLocation:       req.StorageLocation,       // 存放地点
		StorageLocationID:     req.StorageLocationID,     // 存放地点ID
		AssetSource:           req.AssetSource,           // 资产来源
		AssetSourceID:         req.AssetSourceID,         // 资产来源ID
		RegistrationNo:        req.RegistrationNo,        // 注册证书编号
		DocumentNo:            req.DocumentNo,            // 档案编号
		WarrantyPeriod:        req.WarrantyPeriod,        // 保修到期日
		PurchaseDate:          req.PurchaseDate,          // 购买日期
		OriginalAssetCode:     req.OriginalAssetCode,     // 原资产编码
		AssetStatusFlag:       req.AssetStatusFlag,       // 资产状态标识
		UsageRoom:             req.UsageRoom,             // 使用科室
		UsageRoomID:           req.UsageRoomID,           // 使用科室ID
		AssetOwner:            req.AssetOwner,            // 资产负责人
		AssetOwnerID:          req.AssetOwnerID,          // 资产负责人ID
		ImportDate:            req.ImportDate,            // 进口日期
		ManufacturerCode:      req.ManufacturerCode,      // 生产厂家编码
		ManufacturerCodeID:    req.ManufacturerCodeID,    // 生产厂家编码ID
		PositionStandard:      req.PositionStandard,      // 定位标准
		ElectronicTag:         req.ElectronicTag,         // 电子标签
		AssetType:             req.AssetType,             // 资产类型
		FiscalAssetCode:       req.FiscalAssetCode,       //财政资产编码(审核的时候填写)
		FiscalAssetName:       req.FiscalAssetName,       //财政资产名称
		AssetTypeID:           req.AssetTypeID,           // 资产类型ID
		AssetModel:            req.AssetModel,            // 规格型号
		Brand:                 req.Brand,                 // 品牌
		BrandID:               req.BrandID,               // 品牌ID
		WarrantyCertificateNo: req.WarrantyCertificateNo, // 保修凭证编号
		PaymentAmount:         req.PaymentAmount,         // 付款金额
		InvoiceAmount:         req.InvoiceAmount,         // 发票金额
		InvoiceNo:             req.InvoiceNo,             // 发票编号
		ContractNo:            req.ContractNo,            // 合同编号
		SupplierID:            req.SupplierID,            // 供应商ID
		SupplierName:          req.SupplierName,          // 供应商
		ManufacturersID:       req.ManufacturersID,       // 生产商ID
		ManufacturersName:     req.ManufacturersName,     // 生产商
		MaintenanceID:         req.MaintenanceID,         // 维保商ID
		MaintenanceName:       req.MaintenanceName,       // 维保商
		PurchaseOrderID:       req.PurchaseOrderID,       // 采购订单ID
		PurchaseOrderName:     req.PurchaseOrderName,     // 采购订单
		StatusName:            req.StatusName,            // 状态名称
		StockID:               req.StockID,               // 仓库ID
		TenantID:              tenantID,                  // 租户ID
		CreatedAtuser:         userIdStr,                 // 创建用户
		UpdatedAtuser:         userIdStr,                 // 更新用户
		UseDate:               req.UseDate,               //使用日期
		ManageRoom:            req.ManageRoom,            //管理科室
		ManageRoomID:          req.ManageRoomID,          //管理科室ID
		WaysOfChanging:        req.WaysOfChanging,        //变动方式
		WaysOfChangingID:      req.WaysOfChangingID,      //变动方式ID
		Unit:                  req.Unit,                  //单位
		InventoryID:           req.InventoryID,           //入库单ID
		InventoryCode:         req.InventoryCode,         //入库单编码
		IsStock:               req.IsStock,               //是否在库(0 在库/1 出库)
		PurchaseOrderCode:     req.PurchaseOrderCode,     //采购订单编码
		IsManyDepartment:      req.IsManyDepartment,      //是否多科室
		ManyDepartmentID:      req.ManyDepartmentID,      //多科室ID
		ManyDepartmentName:    req.ManyDepartmentName,    //多科室名称
		CurrencyID:            req.CurrencyID,            //币种ID(关联字典表)
		CurrencyName:          req.CurrencyName,          //币种名称
		ManyDepartmentRate:    req.ManyDepartmentRate,    //多科室占比
		BindingCode:           req.BindingCode,           //科目分类编码
		BindingName:           req.BindingName,           //科目分类名称
	})
	// 如果服务层返回错误，返回统一的错误响应
	if err != nil {
		return result.Err(err).End()
	}

	resp, err = result.Suc(res).End()
	//获取调用返回的id
	resp.Data = map[string]any{
		"id": res.Id,
	}
	// 返回成功的响应
	return resp, err
}
